<?php ob_start();?>
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
include($root.'/standart/head.php');
include($root.'/standart/dateHeader.php');
include($root.'/standart/checkUser.php');
$db = connect();
if(isset($_GET["NAME"]) && isset($_GET["UNIT"])){
	$name = $_GET["NAME"];
	$unit = $_GET["UNIT"];
	if(isset($_GET["ID"]) && $_GET["ID"] != ''){
		if(isset($_GET["DELETE"])){
			$stmt ="DELETE FROM INVENTORY
						WHERE ID = ?";
			$statement = $db->prepare($stmt);
			$statement->bind_param('i', $_GET["ID"]);
			if($statement->execute()){
				echo '<span style="color:green; font-weight:bolder;">Kayıt başarıyla silindi</span>';
			} else {
				echo '<span style="color:red; font-weight:bolder;">İşlem sırasında hata alındı </span>';
			}
			$statement->close();
		}else{
			$stmt ="UPDATE INVENTORY 
						SET INVENTORY_NAME = ?, 
							UNIT = ? 
						WHERE ID = ?";
			$statement = $db->prepare($stmt);
			$statement->bind_param('ssi', $name, $unit, $_GET["ID"]);
			if($statement->execute()){
				echo '<span style="color:green; font-weight:bolder;">Kayıt başarıyla güncellendi</span>';
			} else {
				echo '<span style="color:red; font-weight:bolder;">İşlem sırasında hata alındı </span>';
			}
			$statement->close();
		}
	}else{
		$stmt ="INSERT INTO INVENTORY (INVENTORY_NAME, UNIT) VALUES(?,?)";
		$statement = $db->prepare($stmt);
		$statement->bind_param('ss', $name, $unit);
		if($statement->execute()){
			echo '<span style="color:green; font-weight:bolder;">Ürün tipi başarıyla kaydedildi</span>';
		} else {
			echo '<span style="color:red; font-weight:bolder;">Kayıt sırasında hata alındı </span>';
		}
		$statement->close();
	}
}else {
	$stmt ="SELECT INVENTORY.ID, INVENTORY_NAME, UNITS.UNIT_SHORT, UNITS.ID AS UNIT_ID
    			FROM INVENTORY, UNITS
 				WHERE INVENTORY.UNIT = UNITS.ID";
	$res = $db->query($stmt) or die($stmt."<br/><br/>".mysql_error());
	echo "<option value=''>Seçiniz</option>";
	if(isset($_GET['onlyId'])){
	    while($row = $res->fetch_assoc()){
	    	echo '<option value="'.$row['ID'].'">'.$row['INVENTORY_NAME'].'</option>';
	    }
	}else{
		while($row = $res->fetch_assoc()){
			echo '<option value="'.$row['ID'].'-'.$row['UNIT_SHORT'].'-'.$row['UNIT_ID'].'">'.$row['INVENTORY_NAME'].'</option>';
		}
	}
    $res->close();
}
disconnect($db);
?>
<?php ob_end_flush(); ?>